<template>
  <div class="right-content">
    <div class="search">
      <el-button type="primary" @click="handleAdd" size="small" v-hasPermi="['editor:documentInfo:add']"
        >新建文件</el-button
      >
      <el-form :inline="true" :model="queryParams" class="custom-inline-form">
        <div class="center">
          <div class="text-left">
            <el-form-item label="文件编号">
              <el-input
                size="small"
                clearable
                v-model="queryParams.standardNo"
                placeholder="请输入"
                @keyup.enter.native="handleQuery"
              ></el-input>
            </el-form-item>
            <el-form-item label="文件名称">
              <el-input
                size="small"
                clearable
                v-model="queryParams.docName"
                placeholder="请输入"
                @keyup.enter.native="handleQuery"
              ></el-input>
            </el-form-item>
            <el-form-item label="文件状态">
              <el-select
                clearable
                size="small"
                v-model="queryParams.status"
                placeholder="请选择"
              >
                <!-- 1编辑中 2审核中 3已驳回 4待发布 5发布中 6发布成功 7发布失败 8限用 -->
                <el-option label="编辑中" :value="1"></el-option>
                <!-- <el-option label="审核中" :value="2"></el-option> -->
                <el-option label="已驳回" :value="3"></el-option>
                <el-option label="待发布" :value="4"></el-option>
                <el-option label="发布中" :value="5"></el-option>
                <el-option label="发布成功" :value="6"></el-option>
                <el-option label="发布失败" :value="7"></el-option>
                <el-option label="限用" :value="8"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="text-left" v-show="expanded">
            <el-form-item label="文件标识">
              <el-input
                size="small"
                clearable
                v-model="queryParams.docNo"
                placeholder="请输入"
                @keyup.enter.native="handleQuery"
              ></el-input>
            </el-form-item>
            <el-form-item label="负责人">
              <el-input
                size="small"
                clearable
                v-model="queryParams.createBy"
                placeholder="请输入"
                @keyup.enter.native="handleQuery"
              ></el-input>
            </el-form-item>
            <el-form-item label="发布日期">
              <el-date-picker
                size="small"
                style="width: 220px"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                v-model="queryParams.publishTime"
              ></el-date-picker>
            </el-form-item>
          </div>
        </div>

        <div class="right">
          <el-form-item>
            <el-button type="primary" plain  size="mini" @click="handleQuery"
              >查询</el-button
            >
            <el-button type="primary" plain  size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button type="text"  size="mini" @click="toggleExpanded"
              >展开</el-button
            >
          </el-form-item>
        </div>
      </el-form>
    </div>

    <el-table :data="dataList">
      <el-table-column
        label="序号"
        type="index"
        width="50"
        :index="indexMethod"
      />
      <el-table-column label="文件标识" prop="docNo" />
      <el-table-column label="文件名称" prop="docName" />
      <el-table-column label="文件编号" prop="standardNo" />
      <el-table-column label="版本号" prop="standardVersion" width="80" />
      <el-table-column label="文件状态" prop="statusName" width="100" />
      <el-table-column label="负责人" prop="createBy">
        <template slot-scope="scope">
          {{ scope.row.createByName }}/{{ scope.row.createBy }}
        </template>
      </el-table-column>
      <el-table-column label="发布部门" prop="createDept" />
      <el-table-column label="发布日期" prop="publishTime" width="100" />
      <el-table-column label="引用模板" prop="templateName" />
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handlePreview(scope.row)"
            >预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleEditContext(scope.row)" v-hasPermi="['editor:documentInfo:editContent']"
            >编辑正文</el-button
          >
          <el-button size="mini" type="text" @click="handlePublish(scope.row)" v-if="isAdmin || scope.row.hasOpPermission" v-hasPermi="['editor:documentInfo:publish']"
            >发布</el-button
          >
          <el-dropdown size="mini" v-if="isAdmin || scope.row.hasOpPermission" @command="(c) => handleCommand(c, scope.row)">
            <span class="el-dropdown-link"
                v-hasPermi="[
                  'editor:documentInfo:editInfo',
                  'editor:documentPublishRecord:list',
                  scope.row.status === 6 ? '*:*:*' : 'editor:documentInfo:download',
                  'editor:documentInfo:upgrade',
                  'editor:documentInfo:remove',
                ]"
            >
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1" v-hasPermi="['editor:documentInfo:editInfo']">编辑信息</el-dropdown-item>
              <el-dropdown-item command="2" v-hasPermi="['editor:documentPublishRecord:list']">发布记录</el-dropdown-item>
              <el-dropdown-item command="3" v-if="scope.row.status === 6">下载</el-dropdown-item>
              <el-dropdown-item command="4" v-hasPermi="['editor:documentInfo:upgrade']">升版</el-dropdown-item>
              <el-dropdown-item command="5" v-hasPermi="['editor:documentInfo:remove']">删除</el-dropdown-item>
              <!-- <el-dropdown-item command="6">提交审核</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="business-pager p20 fr"
      v-show="dataTotal > 0"
      :background="true"
      :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize"
      :layout="'total, sizes, prev, pager, next, jumper'"
      :page-sizes="[10, 30, 50, 100]"
      :pager-count="7"
      :total="dataTotal"
      @size-change="handleSizeChange"
      @current-change="handlepageNumChange"
    />
    <DocEditModal
      :visible.sync="editModalShow"
      :editData="editData"
      @onClose="onCloseDialog"
      :selectedNode="selectedNode"
      @onSuccess="onSuccess"
    />

    <UserSelectionModal
      :visible.sync="userSelectionModalVisible"
      @onChange="handleAudit"
    />

    <DocPublishHistoryModal
      :visible.sync="docPublishHistoryModalVisible"
      :docNo="currentRow.docNo"
      @update:visible="onSearch"
    />
  </div>
</template>
<script>
import qs from "qs";
import { Message, MessageBox } from "element-ui";
import DocEditModal from "./DocEditModal";
import DocPublishHistoryModal from "./DocPublishHistoryModal";
import {
  getDocList,
  getDocInfo,
  postAudit,
  deleteDoc,
  publishDoc,
  upgradeDoc,
} from "@/api/business";
import UserSelectionModal from "./UserSelectionModal.vue";

export default {
  name: "RightContent",
  components: { DocEditModal, UserSelectionModal, DocPublishHistoryModal },
  props: {
    selectedNode: {
      type: Object,
      default: () => ({}),
    },
    openEditor: {
      type: Function,
      default: () => {},
    },
  },
  watch: {
    selectedNode(node) {
      this.queryParams.classifyId = node.id;
      this.onSearch();
    },
  },
  data() {
    return {
      editModalShow: false,
      editData: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        publishTime: [],
      },
      dataList: [],
      dataTotal: 0,
      loading: false,
      userSelectionModalVisible: false,
      docPublishHistoryModalVisible: false,
      currentRow: {},
      expanded: false,
    };
  },
  computed: {
    isAdmin() {
      return this.$store.getters.permissions?.[0] === "*:*:*"
    }
  },
  mounted() {
    this.handleQuery();
  },
  methods: {
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    toggleExpanded() {
      this.expanded = !this.expanded;
    },
    handleAdd() {
      if (!this.selectedNode.id) {
        return Message.error('请先选择分类节点')
      }
      this.editData = {};
      this.editModalShow = true;
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        publishTime: [],
      };
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.onSearch();
    },
    onSearch() {
      this.loading = true;
      const { publishTime, ...rest } = this.queryParams;
      const [publishStartTime, publishEndTime] = publishTime || [];
      getDocList({
        publishStartTime,
        publishEndTime,
        ...rest,
      })
        .then((res) => {
          this.dataList = res.data.list;
          this.dataTotal = res.data.count;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handlePreview(row) {
      const query = qs.stringify({
        docNo: row.docNo,
        editContentType: "document",
        entry: "preview",
      });
      window.open(`/editor/view?` + query, "_blank");
    },
    handleEditContext(row) {
      const query = qs.stringify({
        docNo: row.docNo,
        editContentType: "document",
      });
      window.open(`/editor/view?` + query, "_blank");
    },
    handleShowUserDialog(row) {
      this.userSelectionModalVisible = true;
      this.currentRow = row;
    },
    async handlePublish(row) {
      try {
        await MessageBox.confirm(`此操作将发布文件，是否继续？`, '提示', {
          type: 'warning'
        })
        await publishDoc({
          docNo: row.docNo,
        });
        Message.success("提交发布成功");
        this.onSearch();
      } catch (error) {
        console.debug(error);
      }
    },
    async handleAudit(user) {
      await postAudit({
        auditorName: user.userName,
        auditorNo: user.userNo,
        docNo: this.currentRow.docNo,
      });
      Message.success("提交审核成功");
      this.onSearch();
    },
    async handleDelete(row) {
      try {
        await MessageBox.confirm(`此操作将删除文件，是否继续`, "提示", {
          type: "warning",
        });
        await deleteDoc(row.docNo);
        Message.success("删除成功");
        this.onSearch();
      } catch (error) {
        console.log("已取消删除");
      }
    },
    handleEditInfo(data) {
      getDocInfo({ docNo: data.docNo }).then((res) => {
        this.editData = res.data;
        this.editModalShow = true;
      });
    },
    handleDownload(row) {
      window.open('/prod-api/editor/file/preview/' + row.publicFilePath, "_blank");
    },
    async handleUpgrade(row) {
      try {
        await MessageBox.confirm(`此操作将升版该文档，是否继续`, "提示", {
          type: "warning",
        });
        await upgradeDoc({ docNo: row.docNo });
        this.onSearch();
      } catch (error) {
        console.debug("已取消操作");
      }
    },
    handleCommand(command, row) {
      switch (command) {
        case "1": // 编辑信息
          this.handleEditInfo(row);
          break;
        case "2": // 发布记录
          this.currentRow = row;
          this.docPublishHistoryModalVisible = true
          break;
        case "3": // 下载
          this.handleDownload(row);
          break;
        case "4": // 升版
          this.handleUpgrade(row);
          break;
        case "5": // 删除
          this.handleDelete(row);
          break;
        case "6": // 提交审核
          this.handleShowUserDialog(row);
      }
    },
    onCloseDialog() {
      this.editData = {};
    },
    onSuccess() {
      this.editData = {};
      this.handleQuery();
    },

    handleSizeChange(val) {
      if (this.queryParams.pageSize * val > this.dataTotal) {
        this.queryParams.pageNum = 1;
      }
      this.onSearch();
    },
    handlepageNumChange() {
      this.onSearch();
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/editor.scss";
.editor-business-page .right-content .search {
  height: auto;
}
::v-deep .custom-inline-form {
  flex: 1;
  display: inline-flex;
  justify-content: flex-end;
}
::v-deep .custom-inline-form .el-form-item {
  margin-bottom: 0;
}
.align-start {
  align-self: start;
}
.right {
  flex-basis: 175px;
}
</style>
